#!/usr/bin/env python
# # -*- coding: utf-8 -*-

"""
@File:      IntegrityCheckTool.py
@Author:    Jim.Dai.Cn
@Date:      2024/6/11 19:14
@Desc:         
"""


from datetime import datetime

import pytz
from qwen_agent.tools.base import BaseTool, register_tool
import json5
import urllib.parse
import ast
import copy
from qwen_agent.agents import Assistant
from ..config.config import *
from ..utils.global_functions import *

'''
    完整性检查： 此次接续采购周期为年
'''


@register_tool('integrity_check')
class IntegrityCheckTool(BaseTool):
    # The `description` tells the agent the functionality of this tool.
    description = 'Check text integrity errors in a doc file with given path.'
    # The `parameters` tell the agent what input parameters the tool has.
    parameters = [
        {'name': 'path_doc', 'type': 'string', 'description': 'The full of path of doc used for analyse', 'required': True}
    ]

    _instance = None
    assistant = None
    _doc_content = None

    str_baseline = ''
    array_chat_history_baseline = []
    rules = [
        '语句应该完整',
        '不应存在病句'
    ]

    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super(IntegrityCheckTool, cls).__new__(cls)
            cls._instance.__init__(*args, **kwargs)
        return cls._instance

    def __init__(self, *args, **kwargs):
        super(IntegrityCheckTool, self).__init__(*args, **kwargs)

    def call(self, params: str, **kwargs) -> str:
        # `params` are the arguments generated by the LLM agent.
        str_path = json5.loads(params)['path_doc']
        self.assistant = Assistant(llm=llm_cfg_llama_cpp_qwen2_7B,
                                   system_message='你是一位精通Python的招标代理，请对照规则检查用户提供的文本，勿篡改原文，严格以Python列表方式回答问题，直接回答原文内容的数组，不需要任何解释。'
                                   # system_message='你是一位专业的招标代理项目经理，请对照规则检查用户提供的文本，严格按照提示回答问题。只用原文回答，言简意赅。'
                                   # function_list=['value_equal_check', 'value_greater_equal_check', 'code_interpreter']
                                   )
        self._doc_content = read_from_doc_to_string(str_path)
        list_ret = self.find_value_contradiction()
        return list_ret

    def find_value_contradiction(self) -> list:
        # text_2026 = self.llm_get_answer(f"请列出所有与2026年有关的表述。")
        # print(text_2026)
        # return
        self.array_chat_history_baseline = [{'role': 'user', 'content': self._doc_content}]
        arr_result = []
        rule_idx = 1
        for rule in self.rules:
            print(f"        规则检查 #{rule_idx} ：{rule}", end=" ")
            answer = self.llm_get_answer(f"根据规则：{rule}，深入检查语句错误及矛盾，可能有多个错误，不要遗漏任何一处错误，请以列表方式列结果，错误的以字符串列表方式列引起错误的原文，无错误返回空列表。只给结果不需要解释。")
            # answer = self.llm_get_answer(f"根据规则：{rule}，深入检查语句错误及矛盾，可能有多个错误，不要遗漏任何一处错误，请用数组方式列出全部结果，数组中只列原文,不需要其他内容，不要忽略空格，如正常请返回空数组。")
            print(f" => {answer}")
            rule_idx = rule_idx + 1
            if (answer != '[]') and (answer is not None) and (answer != []):
                try:
                    ast_ans = ast.literal_eval(answer)
                    arr_result.append(ast_ans)
                except Exception as e:
                    print(f" => exception {e}")
        print(f"      integrity scanner done, result = {arr_result}")
        return arr_result

    def llm_get_answer(self, question):
        user_text = {'role': 'user', 'content': question}
        tmp_his = copy.deepcopy(self.array_chat_history_baseline)
        tmp_his.append(user_text)
        reply = []
        for response in self.assistant.run(messages=tmp_his):
            reply.extend(response)
        return reply[-1]['content']

